<template>
    <div class="tableRow">
        <el-row class="toolbar">
            <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd"
                       v-permission="'system:dept:add'">
                新增
            </el-button>
            <el-button type="info" icon="el-icon-edit" :disabled="dialog.isBatchEditDisabled" size="mini" plain
                       @click="handleEdit" v-permission="'system:dept:edit'"> 编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" :disabled="dialog.isBatchRemoveDisabled" size="mini" plain
                       @click="handleBatchDelete" v-permission="'system:dept:remove'"> 删除
            </el-button>
        </el-row>
        <tree-table :columns="columns" :data="data" :operates="operates"
                    @handleSelectionChange="handleSelectionChange"/>
        <el-dialog :title="dialog.title" :visible.sync="dialog.dialogFormVisible" :modal-append-to-body="false"
                   :destroy-on-close="false" width="600px">
            <el-form :model="deptModel" ref="deptForm" label-width="100px" :rules="deptFormRules" size="small">
                <el-form-item label="上级部门" prop="parentId">
                    <!--el-tree-select  文档地址 https://ayiaq1.github.io/el-tree-select/website/#/components/ElTreeSelect-->
                    <el-tree-select v-model="deptModel.parentId" :selectParams="dialog.selectParams"
                                    :treeParams="dialog.treeParams"
                                    @searchFun="searchFun" ref="treeSelect"/>
                </el-form-item>

                <el-form-item label="部门名称" prop="deptName">
                    <el-input v-model="deptModel.deptName" placeholder="部门名称"/>
                </el-form-item>

                <el-form-item label="显示排序" prop="orderNum">
                    <el-input-number v-model="deptModel.orderNum" value="1" :min="1" label="显示顺序"/>
                </el-form-item>

                <el-form-item label="负责人" prop="leader">
                    <el-input v-model="deptModel.leader" placeholder="负责人"/>
                </el-form-item>

                <el-form-item label="手机" prop="phone">
                    <el-input v-model="deptModel.phone" prefix-icon="fa fa-phone" placeholder="手机"/>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="deptModel.email" placeholder="邮箱"/>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-switch v-model="deptModel.status" active-color="#13ce66" inactive-color="#ff4949"
                               active-text="正常"
                               inactive-text="停用"
                               active-value="0"
                               inactive-value="1">
                    </el-switch>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog" size="medium">取 消</el-button>
                <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts">
    import {Component, Ref, Vue} from "vue-property-decorator";
    import TreeTable from "@/components/TreeTable/TreeTable.vue";
    import {
        addDept,
        checkDeptNameUnique,
        deptTreeSelectData,
        getDeptTreeTableData,
        removeDept,
        updateDept
    } from "@/api/dept";

    @Component({components: {TreeTable}})
    export default class Dept extends Vue {
        private data: Array<any> = [];
        @Ref("deptForm") private deptForm: any;
        @Ref("treeSelect") private treeSelect: any;

        columns: any = [
            {
                label: "ID",
                prop: "id",
                width: 150
            },
            {
                label: "名称",
                prop: "deptName"
            },
            {
                label: "排序",
                prop: "orderNum"
            },
            {
                label: "状态", prop: "status", sortable: "custom", render: function (createElement, row) {
                    if (row && row.row && row.row.status === "0") {
                        return createElement("el-tag", {
                                attrs: {
                                    type: "success"
                                }
                            }, ["正常"]
                        );
                    } else if (row && row.row && row.row.status === "1") {
                        return createElement("el-tag", {
                                attrs: {
                                    type: "warning"
                                }
                            }, ["停用"]
                        );
                    } else {
                        return createElement("el-tag", {
                                attrs: {
                                    type: "danger"
                                }
                            }, ["未知"]
                        );
                    }
                }
            },
            {label: "创建时间", prop: "createTime", sortable: "custom", width: 160},
            {label: "备注", prop: "remark", sortable: "custom"}
        ];
        operates: any = {
            width: 200,
            fixed: "right",
            list: [
                {
                    label: "编辑",
                    type: "warning",
                    icon: "el-icon-edit",
                    plain: true,
                    disabled: (index, row) => {
                        return false;
                    },
                    permission: "system:menu:edit",
                    method: (index, row) => {
                        this.handleEdit(index, row);
                    }
                },
                {
                    label: "删除",
                    type: "danger",
                    icon: "el-icon-delete",
                    plain: true,
                    disabled: (index, row) => {
                        return false;
                    },
                    permission: "system:menu:remove",
                    method: (index, row) => {
                        this.handleDelete(index, row);
                    }
                }
            ]
        };
        deptModel: any = {
            parentId: 0,
            deptName: "",
            orderNum: 1,
            leader: "",
            phone: "",
            email: "",
            status: "0"
        };
        deptFormRules: any = {
            parentId: [
                {validator: this.validateParentNotSelf, trigger: "change"},
            ],
            deptName: [
                {required: true, message: "部门名称不能为空", trigger: ["blur", "change"]},
                {validator: this.validateDeptNameUnique, trigger: "blur"},
            ],
            leader: [
                {required: true, message: "部门负责人不能为空", trigger: ["blur", "change"]}
            ],
            orderNum: [
                {required: true, message: "显示排序不能为空", trigger: ["blur"]}
            ],
            phone: [
                {
                    required: true,
                    pattern: /^1[345678]\d{9}$/,//可以写正则表达式
                    message: "目前只支持中国大陆的手机号码",
                    trigger: ["blur", "change"]
                }
            ],
            email: [
                {type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}
            ]
        };
        dialog: any = {
            dialogFormVisible: false,
            title: "对话框",
            isEdit: false,
            isBatchEditDisabled: true,
            isBatchRemoveDisabled: true,
            formData: [],
            selectParams: {
                clearable: true,
                placeholder: "请选择上级部门"
            },
            treeParams: {
                clickParent: true,
                filterable: true,
                accordion: true,
                data: [],
                props: {
                    children: "children",
                    label: "label",
                    disabled: "disabled",
                    value: "id"
                }
            }
        };

        /*验证部门名称是否唯一*/
        validateDeptNameUnique(rule: any, value: any, callback: any) {
            checkDeptNameUnique({
                deptName: value,
                id: this.deptModel.id,
                parentId: this.deptModel.parentId
            }).then((res: any) => {
                if (res.data && res.data === '0') {
                    callback();
                } else {
                    callback(new Error("部门已经存在"));
                }
            }).catch((err: any) => {
                console.log(err);
                callback(new Error("部门已经存在"));
            })
        };

        /*上级部门不能是自己本身*/
        validateParentNotSelf(rule: any, value: any, callback: any) {
            if (value === this.deptModel.id) {
                callback(new Error("上级部门不能是自己本身"));
            } else {
                callback();
            }
        };

        /*新增*/
        handleAdd() {
            let self = this;
            self.dialog.title = "新增部门";
            self.dialog.isEdit = false;
            deptTreeSelectData().then((response: any) => {
                if (response.data) {
                    self.dialog.treeParams.data = response.data;
                    self.dialog.dialogFormVisible = true;
                }
            }).catch((e) => {
                console.log(e);
            });
        }

        /*编辑*/
        handleEdit(index: number, row: any) {
            let self = this;
            self.dialog.title = "编辑部门";
            self.dialog.isEdit = true;
            deptTreeSelectData().then((response: any) => {
                self.deptModel = Object.assign({}, row || this.dialog.formData[0]);
                if (response.data) {
                    self.dialog.treeParams.data = response.data;
                    self.dialog.dialogFormVisible = true;
                }
            }).catch((e) => {
                console.log(e);
            });
        }

        /*批量删除*/
        handleBatchDelete() {
            let self = this;
            //删除
            self.$confirm("确定要删除选定部门吗？", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                let ids: Array<any> = [];
                self.dialog.formData.forEach((item, index) => {
                    ids[index] = item.id;
                });
                return removeDept({"ids": ids});
            }).then((response: any) => {
                self.getData();
                self.$message.success(response.msg);
            }).catch((e) => {
                console.log(e);
            });
        }

        /*删除*/
        handleDelete(index: number, row: any) {
            let self = this;
            self.$confirm("确定要删除该部门吗？", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                return removeDept({"ids": [row.id]});
            }).then((response: any) => {
                self.getData();
                self.$message.success(response.msg);
            }).catch((e) => {
                console.log(e);
            });
        }

        submitForm(): void {
            let self = this;
            self.deptForm.validate((valid: boolean) => {
                if (valid) {
                    delete self.deptModel.children;
                    if (self.dialog.isEdit) {
                        //编辑
                        updateDept(self.deptModel).then((response: any) => {
                            self.getData();
                            self.reset();
                            self.dialog.dialogFormVisible = false;
                            self.$message.success(response.msg);
                        }).catch((e) => {
                            console.log(e);
                        });
                    } else {
                        //新增
                        addDept(self.deptModel).then((response: any) => {
                            self.getData();
                            self.reset();
                            self.dialog.dialogFormVisible = false;
                            self.$message.success(response.msg);
                        }).catch((e) => {
                            console.log(e);
                        });
                    }
                }
            });
        }


        /*选中事件*/
        handleSelectionChange(val): void {
            if (val) {
                this.dialog.isBatchRemoveDisabled = val.length <= 0;
                this.dialog.isBatchEditDisabled = val.length !== 1;
            }
            this.dialog.formData = val;
        }

        /*重置表单*/
        reset(): void {
            this.deptModel = {
                parentId: 0,
                deptName: "",
                orderNum: 1,
                leader: "",
                phone: "",
                email: "",
                status: "0"
            };
            (this as any).resetForm("deptForm");
        }

        /*关闭对话框*/
        closeDialog() {
            //关闭对话框
            this.dialog.dialogFormVisible = false;
            this.reset();
        }

        /*获取数据*/
        getData() {
            getDeptTreeTableData().then(response => {
                this.data = response.data;
            }).catch((e) => {
                console.log(e);
            });
        }

        searchFun(value: any): void {
            this.treeSelect.filterFun(value);
        }

        mounted() {
            this.getData();
        }
    }
</script>

<style scoped lang="scss">

</style>

